package cn.xiaolang.function.test_map;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentAndWeakMap {

    private static ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {

//        testConcurrentMap();

//		testWeakHashMap();

        testHashMap();
    }

    public static void testConcurrentMap() throws InterruptedException {
        /**
         * 1.ConcurrentHashMap;多实例线程安全，同时操作互不影响
         */
        Thread t1 = new Thread(() -> {
            map.put("map0", 10);
            map.put("map1", 20);
        });

        Thread t2 = new Thread(() -> {
            map.remove("map0");
            map.put("map1", 30);
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(map);
    }

    public static void testWeakHashMap() {
        Map<String, Object> weakMap = new WeakHashMap<>();
        for (int i = 0; i < 10; i++) {
            weakMap.put("weakMap" + i, i + 10);
        }
        System.out.println(weakMap);
        System.gc();
        System.out.println(weakMap);
    }

    /**
     * 测试map集合
     *
     * @author fuhw
     * @date 2016年6月2日 上午10:36:15
     */
    public static void testHashMap() {
        /**
         * 1.HashMap put,get,remove 都是同步的（基于hashTable实现的）
         * 在同时操作put和remove的时候，会抛出ConcurrentModificationException
         */
        Map<String, Object> hashMap = new HashMap<>();

        for (int i = 0; i < 10; i++) {
            hashMap.put("hashMap" + i, i + 10);
        }

        /**
         * 方式1：正常情况下。在同时操作put和remove时，会抛出异常
         */
        for (Entry<String, Object> entry : hashMap.entrySet()) {
            if (entry.getKey().equals("hashMap0")) {
                hashMap.remove(entry.getKey());
            }
        }

        /**
         * 方式2：用iterator操作remove时正常，iterator默认其他线程
         */
        // for (Iterator<Entry<String, Object>> iterator =
        // hashMap.entrySet().iterator(); iterator.hasNext();) {
        // Entry<String, Object> entry = iterator.nextNode();
        // String key = entry.getKey();
        // if (key.equals("hashMap0")) {
        // iterator.remove();
        // }
        // }
        for (Entry<String, Object> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }

}
